package com.darren.center.design.patterns.command;

import com.darren.center.design.patterns.dto.Context;

import java.util.List;

/**
 * <h3>design-patterns</h3>
 * <p></p>
 *
 * @author : Darren
 * @date : 2021年06月14日 19:49:47
 **/
public abstract class AbstractHandlerChain implements HandlerChain {

    protected List<Handler> handlers;

    @Override
    public void handler(String reqXml, Context context) {
        if (handlers != null && !handlers.isEmpty()) {
            this.initLastHandler(handlers);
            Handler firstHandler = null;
            Handler tmpHandler = null;
            for (int i = 0; i < handlers.size(); i++) {
                if (i == 0) {
                    firstHandler = handlers.get(0);
                } else {
                    if (tmpHandler != null) {//处理sonarlint提示
                        tmpHandler.setHandler(handlers.get(i));
                    }
                }
                tmpHandler = handlers.get(i);
            }
            if (firstHandler != null) {//处理sonarlint提示
                firstHandler.doHandler(reqXml, context);
            }
        }

    }

    @Override
    public void initLastHandler(List<Handler> handlers) {
        Handler handler = handlers.get(handlers.size() - 1);
        handler.setHandler(null);
    }

}

